package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysApplication;
import com.ruoyi.system.domain.vo.InvestigationVo;
import com.ruoyi.system.enums.MessageTypeEnum;
import com.ruoyi.system.enums.ReadTypeEnum;
import com.ruoyi.system.mapper.InvestigationMapper;
import com.ruoyi.system.mapper.SysApplicationMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysApplicationService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.SysUserMessageBo;
import com.ruoyi.system.domain.vo.SysUserMessageVo;
import com.ruoyi.system.domain.SysUserMessage;
import com.ruoyi.system.mapper.SysUserMessageMapper;
import com.ruoyi.system.service.ISysUserMessageService;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 用户消息通知Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-18
 */
@RequiredArgsConstructor
@Service
public class SysUserMessageServiceImpl implements ISysUserMessageService {

    private final SysUserMessageMapper baseMapper;

    private final SysUserMapper userMapper;

    private final InvestigationMapper investigationMapper;

    private final SysApplicationMapper applicationMapper;

    private final ISysUserService sysuserservice;

    private final ISysApplicationService applicationService;

    /**
     * 查询用户消息通知
     */
    @Override
    public SysUserMessageVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户消息通知列表
     */
    @Override
    public TableDataInfo<SysUserMessageVo> queryPageList(SysUserMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserMessage> lqw = buildQueryWrapper(bo);
        Page<SysUserMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (!CollectionUtils.isEmpty(result.getRecords())) {
            List<Long> ids = result.getRecords().stream().map(t -> t.getSender()).collect(Collectors.toList());
            Map<Long, SysUser> users = userMapper.selectBatchIds(ids).stream().collect(Collectors.toMap(u -> u.getUserId(), u -> u));
            result.getRecords().forEach(m -> {
                m.setSenderInfo(users.get(m.getSender()));
            });
            List<Long> investigationIds = result.getRecords().stream()
                .filter(t -> MessageTypeEnum.INVESTIGATION.getValue() == t.getMsgType())
                .filter(t -> StringUtils.isNumeric(t.getContent()))
                .map(t -> Long.valueOf(t.getContent())).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(investigationIds)) {
                Map<String, InvestigationVo> investigationMap = investigationMapper.selectVoBatchIds(investigationIds)
                    .stream().collect(Collectors.toMap(u -> u.getId().toString(), u -> u));
                result.getRecords().stream()
                    .filter(t -> MessageTypeEnum.INVESTIGATION.getValue() == t.getMsgType())
                    .filter(t -> StringUtils.isNumeric(t.getContent()))
                    .forEach(m -> {
                        m.setInvestigation(investigationMap.get(m.getContent()));
                    });
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户消息通知列表
     */
    @Override
    public List<SysUserMessageVo> queryList(SysUserMessageBo bo) {
        LambdaQueryWrapper<SysUserMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserMessage> buildQueryWrapper(SysUserMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserMessage> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getSenderName()), SysUserMessage::getSenderName, bo.getSenderName());
        lqw.eq(bo.getReceiver() != null, SysUserMessage::getReceiver, bo.getReceiver());
        lqw.eq(bo.getMsgType() != null, SysUserMessage::getMsgType, bo.getMsgType());
        lqw.orderByAsc(SysUserMessage::getIsRead);
        lqw.orderByDesc(SysUserMessage::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户消息通知
     */
    @Override
    public Boolean insertByBo(SysUserMessageBo bo) {
        SysUserMessage add = BeanUtil.toBean(bo, SysUserMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean addNotice(SysUserMessageBo bo, String secret) {
        SysApplication application = applicationService.getBySecret(secret);
        if (application == null) {
            throw new IllegalArgumentException("应用不存在");
        }
        return insertByBo(bo);
    }

    /**
     * 修改用户消息通知
     */
    @Override
    public Boolean updateByBo(SysUserMessageBo bo) {
        SysUserMessage update = BeanUtil.toBean(bo, SysUserMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserMessage entity) {
        entity.setIsRead(ReadTypeEnum.UN_READ.getValue());
        //TODO 做一些数据校验,如唯一约束
        String sender = sysuserservice.selectUserNickNameById(entity.getSender());
        if (StringUtils.isBlank(sender)) {
            throw new IllegalStateException("发送人不存在");
        }
        entity.setSenderName(sender);
        String receiver = sysuserservice.selectUserNickNameById(entity.getReceiver());
        if (StringUtils.isBlank(receiver)) {
            throw new IllegalStateException("接收人不存在");
        }
    }

    /**
     * 批量删除用户消息通知
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int clearUnRead(Long userId) {
        return baseMapper.clearUnRead(userId);
    }

    @Override
    public Long getUnReadCount(Long userId) {
        LambdaQueryWrapper<SysUserMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(true, SysUserMessage::getReceiver, userId);
        lqw.eq(true, SysUserMessage::getIsRead, ReadTypeEnum.UN_READ.getValue());
        return baseMapper.selectCount(lqw);
    }
}
